package cn.rongdao.jrkabao.model;

import com.mifengkong.frtools.http.request.HttpFunction;
import com.mifengkong.frtools.http.request.callback.FRBaseObserver;
import com.mifengkong.frtools.util.FRSharedPreferences;
import com.mifengkong.frtools.util.FRString;
import com.mifengkong.greendao.bean.VersionInfo;

import cn.rongdao.jrkabao.BuildConfig;
import cn.rongdao.jrkabao.bean.setting.VersionBean;
import cn.rongdao.jrkabao.constant.SPConstant;
import cn.rongdao.jrkabao.dao.VersionDao;
import cn.rongdao.jrkabao.model.api.BaseKaMaoModel;
import io.reactivex.Observable;
import io.reactivex.Observer;

/**
 * Created by jack on 2017/9/19
 */

public class VersionModel extends BaseKaMaoModel {

    public static VersionModel getInstance() {
        return getPresent(VersionModel.class);
    }

    public void execute() {
        execute(new FRBaseObserver<VersionBean>() {
            @Override
            protected void onBaseNext(VersionBean data) {
                if (!FRString.isEmpty(data.getNew_version()) && !data.getNew_version().equals(BuildConfig.VERSION_NAME)) {
                    setVersionData(data);
                }
            }
        });
    }

    public void execute(Observer<VersionBean> observer) {
        Observable<VersionBean> observable = mServletApi.getVersionInfo(mParams).map(new HttpFunction<VersionBean>());
        toSubscribe(observable, observer);
    }

    public void setVersionData(VersionBean data) {
        if (!FRString.isEmpty(data.getForce_update()) && data.getForce_update().equals("1")) {   //强制更新
            FRSharedPreferences.setStringNotClear(SPConstant.IS_SHOW_UPDATE_POP, "NeedShowPop");
        } else if (!FRString.isEmpty(data.getNeed_update()) && data.getNeed_update().equals("1")) {  //非强制更新
            if (!FRString.isEmpty(VersionDao.getInstance().getNewVersion())
                    && VersionDao.getInstance().getNewVersion().equals(data.getNew_version())) {
                //不弹框
                FRSharedPreferences.setStringNotClear(SPConstant.IS_SHOW_UPDATE_POP, "");
            } else {
                FRSharedPreferences.setStringNotClear(SPConstant.IS_SHOW_UPDATE_POP, "NeedShowPop");
            }
        }
        VersionInfo versionInfo = new VersionInfo(data.getNeed_update(), data.getDownload_url(), data.getForce_update()
                , data.getVersion_info(), data.getNew_version(), data.getVersion_title());
        VersionDao.getInstance().updateVersionInfo(versionInfo);
    }
}